package com.example.demo.controller;

import com.example.demo.common.constant.JwtClaimsConstant;
import com.example.demo.pojo.entity.Result;
import com.example.demo.pojo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.BaseContext;
import com.example.demo.utils.JwtProperties;
import com.example.demo.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.security.auth.login.AccountNotFoundException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api/auth/")
public class Users {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/register")
    public Result register(String username, String password) {
        log.info("开始注册");
        return userService.register(username, password);
    }


    @PostMapping("/login")
    public Result login(String username, String password) throws AccountNotFoundException {
        log.info("开始登录");
        User user = userService.login(username, password);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        return  Result.success(token);
    }

    @PostMapping("/trial")
    public Result trial(HttpServletRequest request) {
        String token1 = request.getHeader(jwtProperties.getUserTokenName());
        log.info("jwt校验:{}", token1);
        if (token1==null || token1.isEmpty()){
            log.info("标记试用");
            //试用后，生成特殊jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.TRIAL, 1);
            String token = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);
            return Result.success(token);
        }
      return Result.error("已有token");
    }

    @GetMapping("/getUser")
    public Result getUser() {
        log.info("开始获取用户信息");
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            return Result.success();
        }
        return Result.success(userService.getBuyId(userId));
    }

}
